<?php
namespace app\common\model;

use think\Exception;
use util\Tree;
use app\common\model\Role as RoleModel;
/**
 * 菜单模型
 */
class Menu extends Base 
{
	protected $autoWriteTimestamp = false;
	protected $insert = ['status'=>1];
	//属性修改器
	protected function setTitleAttr($value)
	{
		return htmlspecialchars($value);
	}

    protected function setUrlAttr($value){
        return strtolower($value);
    }

    /**
     * 获取分类列表
     * @return array
     */
    public static function getList($map = array(), $id = 0){
        $data = self::where($map)->order('id,sort')->select();
        $model = new Tree(array('id', 'pid', 'title', 'fulltitle'));
        $list = $model->getTree($data, intval($id));
        return $list;
    }

    /**
     * 获取主菜单
     * @return array
     */
    public static function getTopmenu(){        
        $cache_tag = 'menu_role_'.session('user_auth.role');      
        $menus = cache($cache_tag);
        if(!$menus){
            $map['hide'] = 0;
            $map['pid'] = 0;
            $map['is_menu'] = 1;
            if(!config('develop_mode')){ // 是否开发者模式
                $map['is_dev'] = 0;
            }
            $menus = self::where($map)->order('sort asc')->field('id,title,url,icon')->select()->toArray();
            foreach ($menus as $key => &$value) {
                //没有访问权限的菜单不显示
                if(!RoleModel::checkAuth($value['id'])){
                    unset($menus[$key]);
                    continue;
                }
                if($value['url'] != ''){
                    $value['url'] = (string)url($value['url']);
                }               
            }
            //非开发模式,缓存菜单
            if(!config('develop_mode')){
                cache($cache_tag, $menus);
            }
        }
        return $menus;
    }

    /**
     * 获取侧栏节点
     * @return array
     */
    public static function getSubmenu(){
        $module = App('http')->getName();;
        $controller = App('request')->controller();
        
        $cache_tag = strtolower('submenu_'.$module.'_'.$controller).'_role_'.session('user_auth.role');
        $submenu = cache($cache_tag);
        if(!$submenu){
            //获取当前节点地址
            $path = self::getPath();
            if(!$path){
                return false;
            }
            //当前顶级节点ID
            $pid = $path[0]['id'];
            $map['hide'] = 0;
            $map['is_menu'] = 1;
            if(!config('develop_mode')) {  //是否开发者模式
                $map['is_dev'] = 0;
            }
            $submenu = self::where($map)->field('id,pid,title,url,tip,icon')->order('sort asc')->select()->toArray();
            foreach ($submenu as $key => &$value) {
                //没有访问权限的菜单不显示
                if(!RoleModel::checkAuth($value['id'])){
                    unset($submenu[$key]);
                    continue;
                }
                if($value['url'] != ''){
                    $value['url'] = (string)url($value['url']);
                }
            }
            
            $submenu = list_to_tree($submenu, 'id', 'pid', 'operater', $pid);
            //非开发模式,缓存菜单
            if(!config('develop_mode')){
                cache($cache_tag, $submenu);
            }                      
        }

        return $submenu;
    }

    /**
     * 获取指定节点ID的位置
     * @return array
     * @throws \think\Exception
     */
    public static function getPath(){
        $module = App('http')->getName();
        $controller = App('request')->controller();
        $action = App('request')->action();

        $cache_tag = 'path_'.$module.'_'.$controller.'_'.$action;

        $path = cache($cache_tag);
        if(!$path){
            //当前操作对应的节点ID
            $id = self::where("pid != 0 and url like '%{$controller}/".$action."%'")->value('id');
            $lists = self::column('id,pid,title,url,tip');
            //获取节点ID是所有父节点
            $path = self::getParents($lists, $id);
            if(empty($path)){
                return false;
            }
            // 非开发模式，缓存菜单
            if(!config('develop_mode')){
                cache($cache_tag, $path);
            }
        }
        return $path;
    }    

    /**
     * 根据子节点返回所有父节点
     * @param  array  $lists 数据集
     * @param  string $id    子节点id
     * @return array
     */
    public static function getParents($lists = [], $id = ''){
        $trees = [];
        foreach ($lists as $value) {
            if ($value['id'] == $id) {
                $trees[] = $value;
                $trees   = array_merge(self::getParents($lists, $value['pid']), $trees);
            }
        }
        return $trees;
    } 
}